<?php
namespace app\web\library;

use cubox\Cubox;
use cubox\Template;
use cubox\Controller;
use cubox\Data;

class WebController extends Controller{

    private string $__cacheName = '';

    public function pageCache($name){
        if ($this->app->baseConfig()->cache??true){
            $this->__cacheName = 'web_page_'.$name;
            $cache = $this->app->cache();

            if ($cache->exists($name)){
                echo $cache->get($name);
                exit();
            }
        }
    }

    public function display($name=''){
        $templateConfig = $this->app->config('template',true);
        $websiteData = $this->app->config('website',true)->toArray();
       
        $this->set('site',$websiteData);
        
        if (!$templateConfig->exists('theme') || $templateConfig->theme==''){
            throw new \Exception('未设置模板路径');
        }

        if ($name == ''){
            throw new \Exception('未设置模板');
        }

        $themePath = ROOT.$templateConfig->theme;
        
        $template = new Template($themePath.DS.$name, $this->data);

        $config  = $this->app->baseConfig();
        if ($config->uploadFileUrl) $template->uploadFileUrl = $config ->uploadFileUrl;
        if ($config->webpackUrl) $template->webpackUrl = $config ->webpackUrl;
        
        $html = $template->getHtml();

        if ($this->__cacheName){
            $cache = $this->app->cache();
            $cache->set($this->__cacheName, $html,  $config->cacheTime??3600);
        }

        echo $html;
    }

    public function error($msg =''){
        $templateConfig = $this->app->config('template',true);

        if (!$templateConfig->exists('error_template') || $templateConfig->error_template==''){
            echo $msg;
            exit;
        }

        $this->set('error',$msg);
        return $this->display($templateConfig->error_template);
    }

    public function page404(){
        $templateConfig = $this->app->config('template',true);

        

        if (!$templateConfig->exists('page404_template') || $templateConfig->page404_template==''){
            header('HTTP/1.1 404 Not Found');
            exit;
        }

        return $this->display($templateConfig->page404_template);
    }


   
}